import React from 'react';
import { ConnectProps } from '@/models/connect';
import PageLoading from '@/components/PageLoading';
import { connect } from 'dva';
import { router, Redirect } from 'umi';
import jwt from 'jsonwebtoken';
import moment from 'moment';
import { stringify } from 'querystring';

interface SecurityLayoutProps extends ConnectProps {
  loading: boolean;
}

interface SecurityLayoutState {
  isReady: boolean;
}

class SecurityLayout extends React.Component<SecurityLayoutProps, SecurityLayoutState> {
  state: SecurityLayoutState = {
    isReady: false,
  };

  componentDidMount() {
    const { dispatch } = this.props;

    this.setState({
      isReady: true,
    });

    const cacheInfo = localStorage.getItem('userInfo');

    if (cacheInfo) {
      const userInfo = JSON.parse(cacheInfo);
      const { token, menus = [] } = userInfo;

      if (token) {
        const payload = jwt.decode(token);

        if (moment().isBefore(moment(payload.exp * 1000))) {
          dispatch({
            type: 'login/setUserInfo',
            payload: userInfo,
          });

          if (window.location.pathname === '/') {
            if (menus.length === 0) {
              router.push('/user/login');
            } else {
              router.push(menus[0].url || '/');
            }
          }
          return;
        }
      }
    }
  }

  render() {
    const { isReady } = this.state;
    const { children, loading, currentUser } = this.props;

    const isLogin = currentUser && currentUser.token;
    const queryString = stringify({
      redirect: window.location.href,
    });

    console.log('loading:', loading);

    if ((!isLogin && loading) || !isReady) {
      return <PageLoading />;
    }

    if (!isLogin && window.location.pathname !== '/user/login') {
      return <Redirect to={`/user/login?${queryString}`} />;
    }

    return children;
  }
}

export default connect(({ login, loading }) => ({
  currentUser: login.userInfo,
  loading: loading.models.login,
}))(SecurityLayout);
